package link.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import java.util.Random;
import link.config.AgentConfig;
import link.model.AgentInfoVo;
import org.an.ku.util.StringUtil;
import org.an.proj.contacts.MyApplication;
import org.an.proj.contacts.R;
import org.an.proj.contacts.ui.MainActivity;

/**
 * 使用服务启前台通知，一种部分机型上有效的拉活方式，系统在kill时不会杀死有前台服务的应用
 */
public class LoginManagerService extends Service {

  public static final int FOREGROUND_NOTIFY_ID = 119;

  private void createForegroundService() {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // FLAG_ACTIVITY_CLEAR_TOP 清除以上的

    // fixme 这里是前台服务，退出的时候这个服务业被干掉了，对于push等的通知而言，我们可以利用TaskStackBuilder来实现，点击返回到主页面
    // http://blog.csdn.net/alone_slfly/article/details/41744323

    PendingIntent pend =
        PendingIntent.getActivity(MyApplication.getInstance(), new Random().nextInt(), intent, 0);
    NotificationCompat.Builder builder =
        new NotificationCompat.Builder(MyApplication.getInstance());
    AgentInfoVo loginResultInfo = AgentConfig.getInstance().getAgentInfo();
    builder.setContentIntent(pend)
        .setSmallIcon(R.drawable.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(MyApplication.getInstance().getResources(),
            R.drawable.ic_launcher))
        .setContentTitle(loginResultInfo == null ? null : StringUtil.trim(loginResultInfo.name))
        .setContentText("您的app正在运行...")
        .setAutoCancel(false) // 禁止自动清除
        .setOngoing(true);
    startForeground(FOREGROUND_NOTIFY_ID, builder.build());
  }

  @Nullable @Override public IBinder onBind(Intent intent) {
    return null;
  }

  public void onCreate() {
    super.onCreate();
    createForegroundService();
  }

  public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
  }

  public void onDestroy() {
    stopForeground(true);
    super.onDestroy();
  }
}
